#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import os.path
import time

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions as EC

from Public.Common.Logger import Logger

logger = Logger(log_name="BasePage.py",
                log_file=f'../../Report/Logs/FriAuto.{time.strftime("%Y%m%d", time.localtime())}.log')


class BasePage:
    """
    封装了selenium的一些基本操作的基本页面类
    """

    def __init__(self, browser_type):
        logger.info("初始化BasePage模块")
        self.driver = self.open_browser(browser_type)

    def open_browser(self, browser_type='chrome'):
        logger.info(f"使用{browser_type}浏览器")
        try:
            if browser_type == 'chrome':
                return webdriver.Chrome(executable_path="../Drivers/chromedriver.exe")
            elif browser_type == "firefox":
                return webdriver.Firefox(executable_path="../Drivers/geckodriver.exe")
            elif browser_type == "edge":
                return webdriver.Edge(executable_path="")
        except Exception:
            logger.error(f"{browser_type}浏览器类型暂不支持！")
            raise NameError(f"Not a {browser_type}")

    def open_url(self, url):
        if url != "":
            logger.info(f"打开链接{url}")
            self.driver.get(url)
            self.driver.maximize_window()
        else:
            logger.error(f"{url}链接输入有误！")
            raise ValueError("Please input a url")

    def wait_ele_visible(self, loc: tuple, page_doc="", time_out=20, poll_frequency=0.5) -> WebElement:
        # 显示等待定位的元素
        # 显示等待20s, 间隔为0.5s
        logger.info(f"等待元素{loc}可见")
        try:
            start = time.time()
            element = WebDriverWait(self.driver, time_out, poll_frequency).until(EC.visibility_of_element_located(loc))
            end = time.time()
            logger.info("开始等待时间点：{}，结束等待时间点：{}，等待时长为：{}s".
                        format(time.strftime("%Y%m%d %H:%M:%S", time.localtime(start)),
                               time.strftime("%Y%m%d %H:%M:%S", time.localtime(end)), end - start))
            logger.info(f"已定位到{page_doc}页面中的{loc}元素")
            return element
        except AttributeError:
            logger.error(f"{self}页面中未找到{loc}元素")
        except TimeoutException:
            logger.error(f"定位{loc}元素超时")

    def wait_ele_presence(self, loc: tuple, page_doc="", time_out=20, poll_frequency=0.5) -> WebElement:
        # 显示等待20s, 间隔为0.5s
        logger.info(f"等待元素{loc}可见")
        try:
            start = time.time()
            element = WebDriverWait(self.driver, time_out, poll_frequency).until(EC.presence_of_element_located(loc))
            end = time.time()
            logger.info("开始等待时间点：{}，结束等待时间点：{}，等待时长为：{}s".
                        format(time.strftime("%Y%m%d %H:%M:%S", time.localtime(start)),
                               time.strftime("%Y%m%d %H:%M:%S", time.localtime(end)), end - start))
            logger.info(f"已定位到{page_doc}页面中的{loc}元素")
            return element
        except AttributeError:
            logger.error(f"{self}页面中未找到{loc}元素")
        except TimeoutException:
            logger.error(f"定位{loc}元素超时")

    def locator(self, loc: tuple, page_doc="", mode=0):
        """
        查询页面元素
        :param page_doc:
        :param loc: 定位的方式以及值的元组。
        :param mode: 定位模式，0为查询元素可见（默认）， 1为查询元素被加载到了dom（不一定可见）
        :return: webdriver.element
        """
        if mode == 0:
            element = self.wait_ele_visible(loc, page_doc)

            return element
        elif mode == 1:
            element = self.wait_ele_presence(loc, page_doc)
            return element

    def input_text(self, loc: tuple, page_doc="", *args):
        """

        :param page_doc:
        :param loc: 定位元组
        :param args:
        :return:
        """
        try:
            element = self.locator(loc, page_doc)
            element.send_keys(*args)
            logger.info(f"输入文字内容{args}")
        except AttributeError:
            logger.error(f"定位{loc}元素失败")

    def run_script(self, src):
        self.driver.execute_script(src)

    def click_element(self, loc, page_doc=""):
        logger.info(f"点击{loc}按钮")
        self.locator(loc, page_doc).click()

    def quit(self):
        """退出浏览器进程"""
        logger.info("退出浏览器")
        self.driver.quit()


if __name__ == "__main__":
    bp = BasePage('chrome')
    bp.open_url("https://www.baidu.com")
    bp.input_text((By.ID, "kw"),"百度首页", "自动化")
    bp.click_element((By.ID, "su"))
    bp.quit()
